package com.cookor.poi.modules.mx.util;

import com.alibaba.fastjson.JSONObject;
import com.cookor.poi.common.utils.IdGen;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class TestUtil {

    public static String apiId = "905k7d2da6";

    public static String apiSalt = "654321";

    public static String apiKey = "9wjofm8vzw0c0tz4i9z5h1cs";

    public static String md5(String text, String salt, String key) throws Exception {
        String md5str = DigestUtils.md5Hex(text + salt + key);
        return md5str;
    }

    @Test
    public void myTest()throws Exception{
        String url = "https://chongzhi.nthink.cn/static/face/upload/a072fab162b841d19408b19364e99ef7.jpg";
        String toBase64 = GetImageStrFromUrl(url);
//        post(toBase64);
        postV2(toBase64);

    }

    public void post(String base64File)throws Exception{
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://chongzhi.nthink.cn/jkkc/api/v1/test/face"); // replace <URL> with your URL
        // add headers
        httpPost.setHeader("User-Agent", "Mozilla/5.0"); // replace with your header
        httpPost.setHeader("apiId", apiId);
        httpPost.setHeader("apiSalt", apiSalt);
        httpPost.setHeader("apiSign", md5(apiId, apiSalt, apiKey));
        // add parameters
        List<NameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair("base64File", base64File)); // replace with your parameters
        HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
        httpPost.setEntity(postParams);
        CloseableHttpResponse response = client.execute(httpPost);
        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);
        client.close();
    }


    /**
     * 将一张网络图片转化成Base64字符串
     * @param imgURL
     * @return
     */
    public static String GetImageStrFromUrl(String imgURL) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgURL);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray());
    }

    public static void postV2(String base64File)throws Exception{
        // 创建URL对象
        URL url = new URL("https://chongzhi.nthink.cn/jkkc/api/v1/test/face");

        // 创建HttpURLConnection对象
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方式为POST
        connection.setRequestMethod("POST");

        // 添加请求头
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("apiId", apiId);
        connection.setRequestProperty("apiSalt", apiSalt);
        connection.setRequestProperty("apiSign", md5(apiId, apiSalt, apiKey));
        // 设置是否向HttpURLConnection输出
        connection.setDoOutput(true);
        String params = "base64File=" + URLEncoder.encode(base64File, StandardCharsets.UTF_8.name());

        // 获取输出流
        OutputStream os = connection.getOutputStream();
        os.write(params.getBytes());
        os.flush();
        os.close();

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        System.out.println(response.toString());

        // 断开连接
        connection.disconnect();
    }

}
